import React, { Component } from "react";
import {
  Button,
  Col,
  Row,
  Checkbox,
  Space,
  Form,
  InputNumber,
} from "antd";
import "../../style/style.less";
import PropTypes from "prop-types";
import TheDialog from "@/components/TheDialog";
import { limitDecimals } from "@/utils/numberFixed2";
import _ from "lodash";
import { apiProductInfoDetailButton } from '@/request/commodity'
import TheImage from '@/components/TheImage'

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

class SkuChange extends Component {
  state = {
    skuData: {
      type: "text", //suk类型 text文字， img图片
    },
    skuType: 1,
    specifications: [],
    tableResult: [],
    dataSource: [],
    maxIndex: 0,
    numResult: [],
    checkedAllStatus: false,
  };

  componentDidMount() {
    this.getData()
  }

  getData = async () => {
    const { id } = this.props
    let res = await apiProductInfoDetailButton({ productId: id })
    if (res.data && res.code === 0) {
      const { productInfo, skuInfo } = res.data
      let productSkuJson = JSON.parse(productInfo.productSkuJson)
      skuInfo.forEach((v, i) => {
        let k = i
        productSkuJson.numResult[i].stock = skuInfo[i].stock
        // productSkuJson.numResult[i].SKUId = skuInfo[i].SKUId
        if (k <= skuInfo.length) {
          if (productSkuJson.numResult[k].imageFile === v.imageFile) {
            productSkuJson.numResult[k].SKUId = v.SKUId
          } else {
            return k = i + 1
          }
        } else {
          return
        }
      })
      if (productSkuJson) {
        let { skuPropertyArray, numResult } = productSkuJson
        this.setState(
          {
            specifications: skuPropertyArray,
            numResult,
          },
          () => {
            this.state.specifications.length > 0 &&
              this.initSpecifications(this.state.specifications, true);
          }
        );
      } else {
        this.state.specifications.length > 0 &&
          this.initSpecifications(this.state.specifications);
      }
    }
  }

  /**
   * @desc
   * */
  skuTypeChange = (e) => {
    const skuType = e.target.value;
    this.setState({ skuType });
  };
  /**
   * @desc sku属性添加
   * */
  skuAdd = () => {
    const specifications = [...this.state.specifications];
    let status = false;
    if (specifications.length) {
      specifications.forEach((v) => {
        if (!v.name || !v.child.length) {
          status = true;
        }
      });
    }
    if (status) {
      return React.$message({
        type: "info",
        content: "请补全商品规格！",
      });
    }
    specifications.push({
      name: "", //规格名称
      child: [],
      inputVal: "",
      isHidden: false,
      isImgShow: false,
      SKUId: "",
    });
    this.setState({ specifications });
  };
  /**
   * @desc 编辑suk名称
   * */
  sukEdit = (e, i) => {
    const specifications = [...this.state.specifications];
    const val = e.target.value;
    // if (!filtering.test(val)) {
    //     return React.$message({
    //         type: 'info',
    //         content: '禁止输入特殊字符'
    //     })
    // }
    specifications[i].name = val;
    this.setState({ specifications });
  };
  /**
   * @desc 是否显示图片信息
   * */
  skuImgChange = (e, index) => {
    const specifications = [...this.state.specifications];
    const checked = e.target.checked;
    if (checked) {
      specifications.map((v, i) => {
        v.isImgShow = i === index;
        return v;
      });
    } else {
      specifications[index].isImgShow = checked;
    }
    this.initSpecifications(specifications, true);
  };
  /**
   * @desc 删除sku项
   * */
  skuDelete = (i) => {
    const specifications = [...this.state.specifications];
    specifications.splice(i, 1);
    this.initSpecifications(specifications, true);
  };
  /**
   * @desc sku每子项添加
   * */
  itemAdd = (i) => {
    const specifications = [...this.state.specifications];
    let status = false;
    let skuStatus = false;
    let skuArr = specifications.map((v) => v.name);
    // if (!filtering.test(specifications[i].inputVal)) {
    //     return React.$message({
    //         type: 'info',
    //         content: '禁止输入特殊字符！'
    //     })
    // }
    if (_.uniq(skuArr).length !== skuArr.length) {
      skuStatus = true;
    }
    if (skuStatus) {
      return React.$message({
        type: "info",
        content: "禁止重复添加商品规格！",
      });
    }
    let skuChildArr = specifications[i].child.map((v) => v.itemName);
    if (skuChildArr.includes(specifications[i].inputVal)) {
      status = true;
    }
    if (status) {
      React.$message({
        type: "info",
        content: "禁止重复添加SKU",
      });
      return;
    }
    if (!specifications[i].name.trim()) {
      React.$message({
        type: "info",
        content: "请输入商品规格名",
      });
      return;
    }
    if (specifications[i].inputVal.trim().length <= 0) {
      React.$message({
        type: "info",
        content: "请输入名称",
      });
      return;
    }
    specifications[i].child.push({
      name: specifications[i].name,
      itemName: specifications[i].inputVal,
      imageFile: "",
      skuOriginalPrice: "",
      // stock: "",
      skuCurrentPrice: "",
      fileList: [],
    });
    let arr = this.DescartesData(specifications);
    let numberResult = [];
    arr.forEach((v, i) => {
      numberResult.push({
        skuOriginalPrice: "",
        // stock: "",
        skuCurrentPrice: "",
        imageFile: "",
        isChecked: false,
        fileList: [],
      });
    });

    this.setState(
      {
        numResult: numberResult,
      },
      () => {
        this.initSpecifications(specifications, true);
        this.state.numResult.forEach((v, i) => {
          this.onUpload([], i);
        });
      }
    );
    specifications[i].inputVal = "";
  };
  /**
   * @desc sku每子项输入框修改
   * */
  itemChange = (e, i) => {
    const specifications = JSON.parse(
      JSON.stringify(this.state.specifications)
    );
    specifications[i].inputVal = e.target.value;
    this.setState({ specifications });
  };
  /**
   * @desc 子项删除事件
   * */
  itemDelete = (e, parentIndex, nowIndex) => {
    const specifications = JSON.parse(
      JSON.stringify(this.state.specifications)
    );
    const numResult = [...this.state.numResult];
    specifications[parentIndex].child.splice(nowIndex, 1);
    numResult.splice(nowIndex, 1);
    this.setState(
      {
        numResult,
      },
      () => this.initSpecifications(specifications, true, true)
    );
  };
  /**
   * @desc 子项编辑事件
   * */
  itemEdit = (e, parentIndex, nowIndex) => {
    const specifications = JSON.parse(
      JSON.stringify(this.state.specifications)
    );
    const val = specifications[parentIndex].child[nowIndex].itemName;
    specifications[parentIndex].inputVal = val;
    specifications[parentIndex].child.splice(nowIndex, 1);
    this.initSpecifications(specifications, true);
  };
  /**
   * @desc  规格设置表格数据初始化
   * */
  initSpecifications = (
    specifications = this.state.specifications,
    type,
    isDefault
  ) => {
    const tableResult = this.DescartesData(specifications);
    if (type) {
      this.setState({ specifications, tableResult });
    } else {
      this.setState({
        specifications,
        tableResult:
          tableResult.length === 0 ? this.state.tableResult : tableResult,
      });
    }
    this.props.getNumResult(this.numResultChange(specifications, isDefault));
    this.props.getSkuProperty(specifications, tableResult);
  };

  /**
   * @desc 重新渲染
   * */
  numResultChange(specifications, isDefault) {
    let res = this.DescartesData(specifications) || [];
    let numResult = JSON.parse(JSON.stringify(this.state.numResult));
    let defaultData = {
      imageFile: "",
      skuOriginalPrice: "",
      // stock: "",
      skuCurrentPrice: "",
      isChecked: false,
      fileList: [],
    };
    res = res.map((v) => {
      return defaultData;
    });
    numResult.forEach((v, i) => {
      res.forEach((m, n) => {
        if (i === n) {
          res[i] = v;
        }
      });
    });
    if (isDefault) {
      res = res.map((v) => {
        return defaultData;
      });
    }
    this.setState({ numResult: res });
    return res;
  }

  /**
   * @desc 获取上传图片返回值
   * */
  getFileResult = (data, parentIndex, nowIndex) => {
    const specifications = [...this.state.specifications];
    if (data.length > 0 && data[0].response) {
      const fileId = data[0].response.data;
      specifications[parentIndex].child[nowIndex].img = fileId;
      this.initSpecifications(specifications, true);
    } else {
      specifications[parentIndex].child[nowIndex].img = "";
    }
  };

  /**
   * @desc 转换数据为笛卡尔数据模式
   * */
  DescartesData(arr) {
    //编辑原数组格式
    if (arr.length) {
      if (arr[0].child) {
        arr = arr.map((item) => {
          return (item = item.child);
        });
      }
      if (arr.length === 1) {
        //最终合并成一个
        return arr[0];
      } else {
        //有两个子数组就合并
        let arrySon = [];
        //将组合放到新数组中
        arr[0].forEach((_, index) => {
          arr[1].forEach((_, index1) => {
            arrySon.push([].concat(arr[0][index], arr[1][index1]));
          });
        });
        // 新数组并入原数组,去除合并的前两个数组
        arr[0] = arrySon;
        arr.splice(1, 1);
        // 递归
        return this.DescartesData(arr);
      }
    }
  }

  /**
   * @desc 设置suk综合属性 原价，库存，编码数据
   * */
  inputChange = (e, i, type) => {
    const val = e;
    const numResult = JSON.parse(JSON.stringify(this.state.numResult));
    numResult[i][type] = val;
    this.props.getNumResult(numResult);
    this.setState({ numResult });
  };
  /**
   * @desc 全选事件
   * */
  allChecked = (status) => {
    let numResult = [...this.state.numResult].map((v) => {
      v.isChecked = status;
      return v;
    });
    this.setState({
      checkedAllStatus: status,
      numResult,
    });
  };
  /**
   * @desc sukCheck选中事件
   * */
  checkboxChange = (e, i, type) => {
    const val = e.target.checked;
    const numResult = [...this.state.numResult];
    numResult[i][type] = val;
    let tmp = numResult.filter((v) => v.isChecked);
    this.setState({
      numResult,
      checkedAllStatus: tmp.length === numResult.length,
    });
  };
  /**
   * @desc 批量设置数据
   * */
  bulkSetData = (type) => {
    if (this.state.numResult.filter((v) => v.isChecked).length <= 0) {
      React.$message({
        type: "info",
        content: "请选择商品sku",
      });
      return;
    }
    let title = "";
    // if (type === "stock") {
    //   title = "批量设置库存";
    // } else 
    if (type === "skuCurrentPrice") {
      title = "批量设置价格";
    }
    this.setState({
      title,
      type,
      dialogStatus: true,
    });
  };
  /**
   * @desc 批量设置数据提交方法
   * */
  bulkSave = (value) => {
    if (this.state.numResult.length <= 0) {
      React.$message({
        type: "info",
        content: "请选择商品sku",
      });
      return;
    }
    const numResult = [...this.state.numResult].map((v) => {
      if (v.isChecked) {
        v[this.state.type] = value.bulkNum;
      }
      return v;
    });
    this.setState({ numResult, dialogStatus: false });
  };

  onUpload = (data, index) => {
    const { numResult } = this.state;
    let result = JSON.parse(JSON.stringify(numResult));
    if (data.length && data[0].response && data[0].response.code === 0) {
      result[index].imageFile = data[0].response.data;
      result[index].fileList = [{
        name: 'image',
        status: 'done',
        uid: 1,
        url: data[0].response.data
      }]
      this.setState(
        {
          numResult: result,
        },
        () => this.props.getNumResult(this.state.numResult)
      );
    } else {
      result[index].imageFile = "";
      result[index].fileList = [{}]
      this.setState(
        {
          numResult: result,
        },
        () => this.props.getNumResult(this.state.numResult)
      );
    }
  };

  render() {
    let { numResult, checkedAllStatus, dialogStatus, title, type } =
      this.state;
    let arr = this.state.specifications;
    let res = this.state.tableResult || [];
    let row = [];
    let rowspan = res.length;
    for (let n = 0; n < arr.length; n++) {
      row[n] = parseInt(rowspan / arr[n].child.length);
      rowspan = row[n];
    }
    const tdRow = (i) =>
      arr.map((_, j) => {
        let td;
        if (i % row[j] === 0 && row[j] > 1) {
          res[i] &&
            (td = res[i][j] && (
              <td rowSpan={row[j]} key={j}>
                {res[i][j].itemName}
              </td>
            ));
        } else if (row[j] === 1) {
          res[i] &&
            (res[i] instanceof Array
              ? (td = res[i][j] && <td key={j}>{res[i][j].itemName}</td>)
              : (td = <td key={j}>{res[i].itemName}</td>));
        }
        return td;
      });
    return (
      <>
        <div className="spotGoods-sku-list" style={{ padding: 0 }}>
          {numResult.length > 0 && (
            <div className="spotGoods-sku-item">
              <Row>
                <Col span={24}>
                  <div style={numResult.length >= 5 ? { height: 500, overflowY: 'scroll' } : {}}>
                    <table className="spec-table">
                      <thead>
                        <tr>
                          <th>
                            <Checkbox
                              label={"全选"}
                              onChange={(e) => this.allChecked(e.target.checked)}
                              checked={checkedAllStatus}
                            />
                          </th>
                          {arr
                            .filter((v) => v.name && v.child && v.child.length)
                            .map((th, k) => {
                              return (
                                <th key={k}>
                                  <div className="property-name">{th.name}</div>
                                </th>
                              );
                            })}
                          <th>原价</th>
                          <th>现价</th>
                          {/* <th>库存</th> */}
                          <th>图片</th>
                        </tr>
                        {numResult.map((v, i) => {
                          return (
                            <tr key={i}>
                              <th>
                                <Checkbox
                                  onChange={(e) =>
                                    this.checkboxChange(e, i, "isChecked")
                                  }
                                  checked={v.isChecked}
                                />
                              </th>
                              {tdRow(i)}
                              <td>
                                ￥{_.toNumber(v.skuOriginalPrice).toLocaleString()}
                              </td>
                              <td>
                                ￥{_.toNumber(v.skuCurrentPrice).toLocaleString()}
                              </td>
                              {/* <td>
                                <InputNumber
                                  min={0}
                                  max={10000000}
                                  precision={0}
                                  value={v.stock}
                                  onChange={(e) =>
                                    this.inputChange(e, i, "stock")
                                  }
                                />
                              </td> */}
                              <td>
                                <TheImage src={v.imageFile} width={80} height={80} />
                              </td>
                            </tr>
                          );
                        })}
                      </thead>
                    </table>
                  </div>
                  <div className="spotGoods-btn-box">
                    <Space>
                      <Space>
                        <Button
                          type="primary"
                          onClick={() => this.allChecked(true)}
                        >
                          全选
                        </Button>
                        <Button
                          type="primary"
                          onClick={() => this.allChecked(false)}
                        >
                          取消
                        </Button>
                        <Button
                          className="green-background"
                          onClick={() => this.bulkSetData("stock")}
                        >
                          批量设置库存
                        </Button>
                        {/* <Button
                          className="green-background"
                          onClick={() => this.bulkSetData("skuCurrentPrice")}
                        >
                          批量设置价格
                        </Button> */}
                      </Space>
                    </Space>
                  </div>
                </Col>
              </Row>
            </div>
          )}
        </div>
        <TheDialog
          width={600}
          visible={dialogStatus}
          title={title}
          handleCancel={() => this.setState({ dialogStatus: false })}
          footer={null}
        >
          <Form {...layout} ref={this.fromRef} onFinish={this.bulkSave}>
            <Form.Item
              label={title}
              name="bulkNum"
              rules={[{ required: true }]}
            >
              <InputNumber
                max={10000000}
                min={type === "stock" ? 0 : 0.01}
                precision={type === "stock" ? 0 : 2}
              />
            </Form.Item>
            <div className="p-text-align">
              <Space>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
                <Button onClick={() => this.setState({ dialogStatus: false })}>
                  取消
                </Button>
              </Space>
            </div>
          </Form>
        </TheDialog>
      </>
    );
  }
}

SkuChange.propTypes = {
  getSkuProperty: PropTypes.func,
  getNumResult: PropTypes.func,
  defaultValue: PropTypes.array,
};
SkuChange.defaultProps = {
  defaultValue: [],
};
export default SkuChange;
